import { Injectable, BadRequestException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { GoodsEntity, SkuEntity, StockLogEntity } from './goods.entity'
import { CreateGoodsDto, UpdateGoodsDto } from './dto/goods.dto'

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(GoodsEntity)
    private readonly repo: Repository<GoodsEntity>,
    @InjectRepository(SkuEntity)
    private readonly skuRepo: Repository<SkuEntity>,
    @InjectRepository(StockLogEntity)
    private readonly stockRepo: Repository<StockLogEntity>,
  ) {}

  // 分页列表
  async page(query: any) {
    const pageNum = Number(query.pageNum || 1)
    const pageSize = Number(query.pageSize || 10)
    const where: any = {}
    if (query.title) where.title = Like(`%${query.title}%`)
    if (query.status !== undefined && query.status !== '') where.status = Number(query.status)
    if (query.categoryId) where.categoryId = Number(query.categoryId)
    if (query.supplierId) where.supplierId = Number(query.supplierId)

    const [list, total] = await this.repo.findAndCount({
      where,
      order: { goodsId: 'DESC' },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    })
    return { list, total }
  }

  // 详情
  async findOne(id: number) {
    return this.repo.findOne({ where: { goodsId: id } })
  }

  // 新增
  async create(dto: CreateGoodsDto) {
    const entity = this.repo.create(dto as any)
    return this.repo.save(entity)
  }

  // 更新
  async update(id: number, dto: UpdateGoodsDto) {
    await this.repo.update({ goodsId: id }, dto as any)
    return this.findOne(id)
  }

  // 删除（支持批量）
  async remove(ids: number[]) {
    if (!ids?.length) return
    await this.repo.delete(ids)
  }

  // 状态变更
  async changeStatus(goodsId: number, status: number) {
    await this.repo.update({ goodsId }, { status })
    return this.findOne(goodsId)
  }

  // 审核状态变更：0待审 1通过 2驳回
  async changeAudit(goodsId: number, auditStatus: number) {
    await this.repo.update({ goodsId }, { auditStatus })
    return this.findOne(goodsId)
  }

  // ========== SKU 相关 ==========

  // SKU 列表（按商品）
  async listSku(goodsId: number) {
    if (!goodsId) throw new BadRequestException('goodsId 不能为空')
    return this.skuRepo.find({ where: { goodsId }, order: { skuId: 'ASC' } })
  }

  // 新增 SKU
  async createSku(dto: Partial<SkuEntity>) {
    if (!dto?.goodsId) throw new BadRequestException('goodsId 不能为空')
    if (dto.stock != null && Number(dto.stock) < 0) throw new BadRequestException('库存不能为负数')
    const entity = this.skuRepo.create(dto as any)
    return this.skuRepo.save(entity)
  }

  // 更新 SKU
  async updateSku(skuId: number, dto: Partial<SkuEntity>) {
    await this.skuRepo.update({ skuId }, dto as any)
    return this.skuRepo.findOne({ where: { skuId } })
  }

  // 删除 SKU（支持批量）
  async removeSku(ids: number[]) {
    if (!ids?.length) return
    await this.skuRepo.delete(ids)
  }

  // 库存变更（正数入库，负数出库）
  async changeStock(params: { skuId: number; change: number; bizType: string; bizNo?: string; remark?: string }) {
    const { skuId, change, bizType, bizNo, remark } = params
    if (!skuId) throw new BadRequestException('skuId 不能为空')
    if (!change || change === 0) throw new BadRequestException('变动数量必须非零')
    if (!bizType) throw new BadRequestException('bizType 不能为空')

    // 检查现有库存，避免负库存
    const sku = await this.skuRepo.findOne({ where: { skuId } })
    if (!sku) throw new BadRequestException('SKU 不存在')
    const next = Number(sku.stock) + Number(change)
    if (next < 0) throw new BadRequestException('库存不足')

    // 事务：更新库存 + 记录流水
    await this.skuRepo.manager.transaction(async (manager) => {
      await manager.increment(SkuEntity, { skuId }, 'stock', change)
      const log = manager.create(StockLogEntity, {
        skuId,
        change,
        bizType,
        bizNo,
        remark,
      })
      await manager.save(StockLogEntity, log)
    })
    return this.skuRepo.findOne({ where: { skuId } })
  }
}
